package com.zhilianbao.leyaogo.ui.fragment.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.baseadapter.recycleView.QuickRcvAdapter;
import com.bql.roundview.RoundTextView;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.ActivityApi;
import com.zhilianbao.leyaogo.http.api.ShoppingCartApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.listener.OnAddToCartClickListener;
import com.zhilianbao.leyaogo.model.response.home.SpecialActivityInfo;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.activity.shoppingcart.ShoppingCartActivity;
import com.zhilianbao.leyaogo.ui.adapter.home.SpecialActivityHotAdapter;
import com.zhilianbao.leyaogo.ui.adapter.home.SpecialActivityListAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.RefreshAndLoadFragment;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.ShopAnimationUtils;
import com.zhilianbao.leyaogo.utils.ShopNumUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.view.widgets.MyRelativeLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * ClassName: SpecialActivityListFragment <br>
 * Description: 活动专题详情<br>
 * Author: Cyarie <br>
 * Created: 2016/12/12 17:57 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class SpecialActivityDetailsFragment extends RefreshAndLoadFragment<SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean> implements OnAddToCartClickListener<SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean> {


    @BindView(R.id.tv_activity_info)
    TextView mTvActivityInfo;
    private SpecialActivityListAdapter mSpecialActivityListAdapter;


    private SpecialActivityHotAdapter mSpecialActivityHotAdapter;

    @BindView(R.id.iv_add_to_cart)
    ImageView mIvAddToCart;
    @BindView(R.id.iv_cart_num)
    RoundTextView mIvCartNum;
    @BindView(R.id.rl_add_to_cart)
    RelativeLayout mRlAddToCart;
    @BindView(R.id.rl_content)
    MyRelativeLayout mRlContent;

    private long mActivityId;//活动ID
    //    private int mActivityType;//活动类型 2 专题 3 活动
    private boolean mIsFromShoppingCart;//是否从购物车进来

    private int cartNum;


    public static SpecialActivityDetailsFragment getInstance(Bundle bundle) {
        SpecialActivityDetailsFragment specialActivityListFragment = new SpecialActivityDetailsFragment();
        specialActivityListFragment.setArguments(bundle);
        return specialActivityListFragment;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        //列表活动专题点击
        if (mRcvLoadMore != null && mRcvLoadMore.getAdapter() != null && mRcvLoadMore.getHeaderAndFooterRecyclerViewAdapter().getAdapter() instanceof SpecialActivityListAdapter) {
            //进入商品详情
            Utils.startGoodsDetails(mActivity, (int) mList.get(position).getGoodsId(), (int) mList.get(position).getGoodsSkuId(), mIsFromShoppingCart);
        }
    }

    @OnClick({R.id.iv_add_to_cart})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add_to_cart:
                Utils.startActivity(mActivity, ShoppingCartActivity.class);
                break;
        }
    }

    @Override
    public QuickRcvAdapter<SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean> getAdapter() {
        return mSpecialActivityListAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(mActivity, 2);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_special_activity;
    }

    @Override
    public void onRefresh() {
        loadDataList(1, true);
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        ActivityApi.getActivityDetails(mActivity, mActivityId, curPage, pageSize, new RefreshAndLoadCallback<SpecialActivityInfo>(isPullToRefresh) {
            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                loadDataList(1, false);
            }

            @Override
            public void onResultSuccess(SpecialActivityInfo o, @Nullable Response response, LoadingViewCallback callback) {
                if (o != null) {
                    mTvTitle.setText(o.getActivityType() == 0 ? getString(R.string.topic_details) : getString(R.string.activity_details));
                    mSpecialActivityListAdapter.setActivityType(o.getActivityType());
                    mTvActivityInfo.setVisibility(o.getIsPage() == 0 ? View.VISIBLE : View.GONE);
                    // 0 列表 1 热区
                    if (o.getIsPage() == 0) {
                        mTvActivityInfo.setText(o.getActivityFullName());
                        handleSpecialActivityListData(curPage, callback, o.getMallActivityGoodsSignVoList());
                        mRcvLoadMore.setPadding(0, Utils.dp2px(8), Utils.dp2px(4), Utils.dp2px(4));
                        mRcvLoadMore.setClipToPadding(false);
                        if (curPage == 1 && mList.size() == 0) {
                            mRlAddToCart.setVisibility(View.GONE);
                        } else if (curPage == 1 && mList.size() != 0) {
                            mRlAddToCart.setVisibility(View.VISIBLE);
                        }
                    } else {
                        mSpecialActivityHotAdapter = new SpecialActivityHotAdapter(mActivity, o.getMallActivityPageVoList(), mToolbar != null ? mToolbar.getHeight() : 0, mIsFromShoppingCart);
                        mRcvLoadMore.setLayoutManager(new LinearLayoutManager(mActivity));
                        mRcvLoadMore.setAdapter(mSpecialActivityHotAdapter);
                    }
                } else {
                    callback.showEmpty();
                }

            }
        });
    }

    /**
     * 处理刷新加载得到的数据
     *
     * @param curPage             当前页
     * @param loadingViewCallback 加载视图
     * @param list                数据集合
     */
    public void handleSpecialActivityListData(int curPage, LoadingViewCallback loadingViewCallback, List<SpecialActivityInfo.MallActivityGoodsSignVoListBean> list) {
        mCurPage = curPage;
        if (list.size() == 0 && mCurPage == 1) {
            loadingViewCallback.showEmpty();
        } else {
            if (mCurPage == 1) {
                getAdapter().clear();
            }
            mCurPage = mCurPage + 1;
            List<SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean> goodsListBeen = new ArrayList<>();
            for (SpecialActivityInfo.MallActivityGoodsSignVoListBean mallActivityGoodsSignVoListBean : list) {
                for (SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean activityGoodsListBean : mallActivityGoodsSignVoListBean.getActivityGoodsList()) {
                    goodsListBeen.add(activityGoodsListBean);
                }
            }
            getAdapter().addToLast(goodsListBeen);
            if (mRcvLoadMore != null) {
                if (list.size() < pageSize || list.size() == 0) {
                    mRcvLoadMore.setCanLoadMore(false);
                } else {
                    mRcvLoadMore.setCanLoadMore(true);
                }
            }
        }
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mActivityId = getArguments().getLong(IntentConfig.ACTIVITY_ID, 0);
        mIsFromShoppingCart = getArguments().getBoolean(IntentConfig.IS_FROM_SHOPPING_CART, false);
        mSpecialActivityListAdapter = new SpecialActivityListAdapter(mActivity, mList, this);
        cartNum = LeYaoGoApplication.SHOPPING_CART_NUM;
        ShopNumUtils.show(mIvCartNum, cartNum);
    }

    @Override
    protected void initToolbarHere() {
        //        mActivityType = getArguments().getInt(IntentConfig.ACTIVITY_TYPE, 3);
        initToolbar(getString(R.string.activity_details));
    }

    @Override
    public void onLoadMore() {
        loadDataList(mCurPage, true);
    }

    @Override
    public void onAddToCartClick(SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean item, ImageView imageView) {
        if (Utils.isUserLogin(true, LogicCodeBlock.LogicState.AddToCart.value)) {
            addToCart(item, imageView);

        } else {
            LogicCodeBlock.create().registerLogicCodeCallback(logicState -> {
                if (logicState == LogicCodeBlock.LogicState.AddToCart.value)
                    addToCart(item, imageView);
            });
        }
    }

    /**
     * 加入购物车
     *
     * @param item
     * @param imageView
     */
    private void addToCart(SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean item, ImageView imageView) {
        ShoppingCartApi.setShoppingCart(mActivity, Utils.getUserLoginInfo().getUserId(), item.getGoodsId(), Utils.getSupplierId(), item.getShopId(), item.getGoodsSkuId(), 1, 0, new DialogCallback<GoodsStock>(mActivity/*, getString(R.string.adding)*/) {
            @Override
            public void onSuccess(GoodsStock o, Call call, Response response) {

                ShopAnimationUtils.addToShoppingCart(mActivity, 2, imageView, mIvAddToCart, mRlContent, true, () -> {
                    if (mIsFromShoppingCart) {
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_REFRESH_SHOPPINGCART));
                    } else {
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART));
                    }

                    ShopNumUtils.show(mIvCartNum, ++cartNum);
                });
            }
        });
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_FINISH_GOODS_ACTIVITY://从活动详情,专题详情进入购物车,点击去逛逛,finish掉该页面
                mActivity.finish();
                break;
        }
    }
}
